<template>
  <div class="login-container">
    <el-card class="login-card">
      <div slot="header" class="card-header">
        <h2>用户管理系统</h2>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" @keyup.enter.native="handleLogin"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loading: false,
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$axios.post('/api/users/login', this.loginForm)
              .then(response => {
                console.log('登录响应:', response.data) // 添加调试日志
                if (response.data.success) {
                  // 保存用户信息到本地存储
                  localStorage.setItem('username', response.data.username)
                  localStorage.setItem('userId', response.data.userId)
                  localStorage.setItem('userRole', response.data.role)

                  console.log('保存的角色:', response.data.role) // 添加调试日志
                  console.log('localStorage中的角色:', localStorage.getItem('userRole')) // 验证保存

                  this.$message.success('登录成功')
                  this.$router.push('/home/users')
                } else {
                  this.$message.error(response.data.message || '账号异常，请联系管理员！')
                }
              })
              .catch(error => {
                console.error('Login error:', error)
                this.$message.error('账号异常，请联系管理员！')
              })
              .finally(() => {
                this.loading = false
              })
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-card {
  width: 400px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: #409EFF;
}
</style>